const {ccclass, property} = cc._decorator;

const i18n = require('LanguageData');

import Common  from "./utils/common";

@ccclass
export default class Game extends cc.Component {
    @property(cc.Node)
    kzNode: cc.Node = null;
    @property(cc.Node)
    listNode: cc.Node = null;
    @property(cc.Node)
    scoreNode: cc.Node = null;
    @property(cc.Node)
    gameOver: cc.Node = null;
    @property(cc.Node)
    scoreNode2: cc.Node = null;
    @property(cc.Node)
    outGameBtn: cc.Node = null;
    @property(cc.Node)
    jdaNode: cc.Node = null;

    private data = [];
    private score = 0;
    private time = 5

    onLoad () {
      Common.btnClick(this.kzNode.children[0], ()=>{
        this.choose(1)
      })
      Common.btnClick(this.kzNode.children[1], ()=>{
        this.choose(0)
      })
      Common.btnClick(this.outGameBtn, ()=>{
        this.data = [];
        this.time = 5;
        this.score = 0;
        Common.setLableNodeText(this.score + "", this.scoreNode);
        Common.setLableNodeText(this.score + "", this.scoreNode2);
        this.setJd();
        this.node.active = false;
        this.gameOver.active = false;
      })
    }

    startGame(){
      for(let i = 0; i < 10; i++){
        this.data.push(this.getNextNum());
      }
      this.renderList();

      let t = setInterval(()=>{
        this.time-=0.1;
        if(this.time <= 0){
          this.gameOver.active = true;
          Common.setLableNodeText(this.score + "", this.scoreNode2);
          clearInterval(t);
        }
        this.setJd();
      }, 100)
    }

    setJd(){
      this.jdaNode.width = Number((40 * this.time).toFixed(1));
    }

    choose(type){
      if(type == this.data[0]){
        this.score++;
        Common.setLableNodeText(this.score + "", this.scoreNode);
        if(this.time < 4.8){
          this.time += 0.2;
        }
      }
      this.data.shift();
      this.data.push(this.getNextNum());
      this.renderList();
    }

    getNextNum(){
      return Math.random()> 0.5 ? 1: 0
    }

    renderList(){
      this.data.map((item, i)=>{
        let nodeItem = this.listNode.children[i];
        nodeItem.children[0].children[0].active = item;
        nodeItem.children[1].children[0].active = !item;
      })
    }

}
